import getUrlParams from './getUrlParams';
import { isOptional, isDataTable } from '../components/designer/form/component/typeof';

// 通过字段名称来给字段赋初值, 字段名称唯一
export const setComsValFromUrlParams = coms => {
  const params = getUrlParams();

  for (let key in params) {
    let value = params[key];

    const fieldInfo = key ? key.split('.') : '';
    let detailTable = '';
    let fieldName = '';

    if (fieldInfo.length === 2) {
      detailTable = fieldInfo[0];
      fieldName = fieldInfo[1];
    } else {
      fieldName = fieldInfo[0];
    }

    const ind = coms.findIndex(com => {
      if (detailTable) {
        return com.fieldName === fieldName && com.detailTable === detailTable;
      }

      return com.fieldName === fieldName;
    });

    if (ind >= 0) {
      let curCom = coms[ind];

      curCom = setComVal(curCom, value);
      coms[ind] = curCom;   
    }
  }

  return coms;
}

const formatSelectVal = (com, value) => {
  const { options } = com.config;
  const vals = [];

  options.forEach(({ showname, key }, i) => {

    if (value && value.length > 0 && value.indexOf(showname) > -1 ) {
      vals.push({
        key: key,
        value: showname
      })
    }
  })
  
  return vals;
}

const setComVal = (com, value) => {
  com.config.defaultValue = value;
  com.value = value;
  
  if (isOptional(com)) { // 选择框
    const val = formatSelectVal(com, value);

    com.config.defaultValue = val;
    com.value = val;
  } 

  return com;
}